
package nextel.visita.rms.listener;

 
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.Connector;
import java.io.InputStream;
import java.io.OutputStream;
import nextel.visita.bean.FotoBean;
import pe.com.nextel.rms.DataOutputStreamX;

/**
 *
 * @author dsanchez
 */
public class HttpFoto implements ListenerRMSFoto {
    
    //Valores estaticos del status de la conexion
    public static final int HTTP_TRYING_CONNECTION_STATUS = 0;
    public static final int HTTP_CONNECTED_STATUS = 1;
    public static final int HTTP_DATA_SENDING_STATUS = 2;
    public static final int HTTP_DATA_RECEIVING_STATUS = 3;
    public static final int HTTP_TERMINATED_OK_STATUS = 4;
    public static final int HTTP_CLOSING_STATUS = 5;
    public static final int HTTP_TERMINATED_STATUS = 6;
    private FotoBean fotoBean;
    private String url;
    private Thread thread = null;
//    private HttpListener httpListener = null;
    //private Exception exception = null;
    private volatile int currentStatus = -1;
    private boolean flagEnvio = false;

    /**
     * @param mensajeHttp objeto que encapsula la URL a la que se va conectar
     * y el mensaje de envio. Cuando termina de ejecutarse el proceso HTTP
     * encapsula el mensaje de retorno.
     */
    public HttpFoto(String purl) {
        //this.fotoBean = pfotoBean;
        this.url = purl;
    }

    public HttpFoto() {
    }

    public void setUrl(String purl) {
        this.url = purl;
    }


    private void makeConnection() throws Exception {

       // System.out.println("HttpFoto.makeConnection");

        currentStatus = -1;
//        exception = null;
        HttpConnection conn = null;
        OutputStream out = null;
        InputStream in = null;
        ByteArrayOutputStream stream = null;
        //DataOutputStream os = null;
        DataOutputStreamX os = null;
        try {

            flagEnvio = false;

            if (fotoBean == null) {
                return;
            }

//            int lengthDataTotal =
//                    String.valueOf(fotoBean.getIdUsuario()).length() +
//                    String.valueOf(fotoBean.getCodigoNextel()).length() +
//                    String.valueOf(fotoBean.getFlagPosicion()).length() +
//                    //agregado
//                    String.valueOf(fotoBean.getCodVisita()).length() +
//                    fotoBean.getData().length;
            
            int lengthDataTotal;
            //stream = new ByteArrayOutputStream(lengthDataTotal);
            stream = new ByteArrayOutputStream();
            os = new DataOutputStreamX(stream);
            //os.writeInt(fotoBean.getIdUsuario());
            os.writeString(fotoBean.idUsuario); 
            os.writeString(fotoBean.codigoActividad); 
            os.writeInt(fotoBean.getIdRecodset());            
            os.writeString(fotoBean.fecha); // 
            os.write(fotoBean.data);
            
            //imprime los datos antes de enviar
//            System.out.println(" *****/////*****/////*****/////*****/////*****/////*****");
//            System.out.println("fotoBean.getIdUsuario()=" + fotoBean.idUsuario);
//            System.out.println("fotoBean.codigoNextel=" + fotoBean.getIdRecodset()); 
            System.out.println("fotoBean.fecha()=" + fotoBean.fecha);    
//            System.out.println("fotoBean.getData().length=" + fotoBean.data.length);
//            System.out.println(" *****/////*****/////*****/////*****/////*****/////*****");
            
            byte[] data = stream.toByteArray();
            lengthDataTotal = data.length;

//            System.out.println("url=" + url);
            conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);

            conn.setRequestMethod(HttpConnection.POST);
            //conn.setRequestProperty("Connection", "Close");
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("Pragma", "no-cache");
            conn.setRequestProperty("Expires", "Tue, 1 Jul 1997 00:00:00 GMT");

            conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(lengthDataTotal));

            System.out.println("String.valueOf(data.length)=" + lengthDataTotal);
            //OUT
            out = conn.openOutputStream();            
            currentStatus = HTTP_DATA_SENDING_STATUS;

            int size = 512;
            int index = 0;
            int dataLength = lengthDataTotal;            
            
            while (dataLength > 0 && fotoBean.data.length > 0 ) {  //ARRARY DE FOTOS > 0 
                if (size > dataLength) {
                    size = dataLength;
                }               
                
                out.write(data, index, size);
                dataLength -= size;
                index += size;
            }
            
            out.flush();
 
//            if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
//                currentStatus = HTTP_CONNECTED_STATUS;
//                System.out.println("*/*/*//*/*/*///*/*/*/*/*data getResponseCode OK");
//            }
//            System.out.println("enviado al servidor 1" + System.currentTimeMillis( ));
//            
///*********************************************************************
///                 TIMEOUT            
///*********************************************************************
//            System.out.println("enviado al servidor 2" + System.currentTimeMillis( ));
            //IN
            currentStatus = HTTP_DATA_RECEIVING_STATUS;
            

            in = conn.openInputStream();
//            System.out.println("enviado al servidor 3" + System.currentTimeMillis( ));
//            System.out.println("Respuesta conn.getLength()=" + conn.getLength());
//            mensajeHttp.setLongitud(conn.getLength());


            if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
//                System.out.println("--------------ok--------------");
                //System.out.println("limpiar datos");
                flagEnvio = true;
//                mensajeHttp.setInput(in);
            } else {
                System.out.println("RESPONSE CODE -: " + conn.getResponseCode());

                StringBuffer sbRespuesta = new StringBuffer();
                byte[] arrByte = new byte[1024];
                int len;
                while ((len = in.read(arrByte)) != -1) {
                    sbRespuesta.append(new String(arrByte, 0, len));
                }
                System.out.println(sbRespuesta.toString());
            }
            currentStatus = HTTP_TERMINATED_OK_STATUS;
//            if (httpListener != null) {
//                httpListener.receiveStatus(this, currentStatus);
//            }
        } catch (Exception exp) {
            exp.printStackTrace();
//            exception = exp;
//            if (httpListener != null) {
//                httpListener.receiveError(this, exception);
//            }
        } finally {

            if (os != null) {
                try {
                    os.close();
                    os = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (stream != null) {
                try {
                    stream.close();
                    stream = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                in = null;
            }

            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                out = null;
            }

            if (conn != null) {
                try {

                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                conn = null;
            }
        }

//        if ((exception != null) && (httpListener == null)) {
//            throw exception;
//        }

        currentStatus = HTTP_TERMINATED_STATUS;
//        if (httpListener != null) {
//            httpListener.receiveStatus(this, currentStatus);
//        }
    }

    public void run() {
        try {
            makeConnection();
        } catch (Exception e) {
            e.printStackTrace( );
//            if (httpListener != null) {
//                httpListener.receiveError(this, e);
//            }
        }
//        thread = null;
    }


    public synchronized  void enviarFoto(FotoBean ftbean) {
        //System.out.println("RMSFoto - enviarFoto");
        
        this.fotoBean = ftbean;
//        connect();
        run();
    }

    public boolean envioCorrecto() {
        return flagEnvio;
    }
    
}
